package dormouse.vfs.ui;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.swing.JTree;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;

import org.apache.commons.collections.iterators.ListIteratorWrapper;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.VFS;

/**
 * This class creates a tree containing a file hierarchy.
 * 
 * @author mfortner
 * @version $Revision$
 */
public class FileTree extends JTree {

	/**
	 * 
	 */
	private static final long serialVersionUID = -6652119938758163837L;

	/**
	 * Constructor
	 *
	 */
	public FileTree() {
		super(new DefaultFileTreeModel(new DefaultMutableTreeNode(),
				DefaultFileTreeModel.DEFAULT_ROOTS));
		jbInit();
	}

	/**
	 * Constructor
	 * @param dir
	 */
	public FileTree(FileObject dir) {
		this(new DefaultFileTreeModel(dir));
	}

	/**
	 * Constructor.
	 * 
	 * @param model
	 */
	public FileTree(DefaultFileTreeModel model) {
		super(model);
		jbInit();
	}

	public void jbInit() {
		TreeSelectionModel tsModel = this.getSelectionModel();
		tsModel.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);

	}

	public void addTreeSelectionListener(TreeSelectionListener arg0) {
		super.addTreeSelectionListener(arg0);
	}

	public void setSelectedDir(String dir) throws FileSystemException {
		this.setSelectionPath(new FileTreePath(dir));
	}

	public void setSelectedDir(FileObject dir) {
		this.setModel(new DefaultFileTreeModel(dir));
		// this.setSelectionPath(new FileTreePath(dir));
	}

	class FileTreePath extends TreePath {
		/**
		 * 
		 */
		private static final long serialVersionUID = -3668818670297946958L;

		/**
		 * Constructor
		 * 
		 * @param dir
		 * @throws FileSystemException
		 */
		public FileTreePath(String dir) throws FileSystemException {
			this(VFS.getManager().resolveFile(dir));
		}

		/**
		 * Constructor
		 * 
		 * @param xdir
		 */
		public FileTreePath(FileObject xdir) {

			try {
				xdir.getName().getPath();

				FileObject parent = xdir.getParent();
				List<FileObject> list = new ArrayList<FileObject>();

				while (parent != null) {
					list.add(parent);
					parent = xdir.getParent();
				}

				Iterator<FileObject> it = list.iterator();
				ListIteratorWrapper itw = new ListIteratorWrapper(it);

				FileObject currdir = xdir;
				String currname = null;

				while (itw.hasPrevious()) {
					currdir = (FileObject) itw.previous();
					currname = currdir.getName().toString();
					if (currname != null && !currname.equals("")) {
						System.out.println("adding: " + currname);
						this.pathByAddingChild(currname);
					}

				}
			} catch (FileSystemException e) {
				e.printStackTrace();
			}

		}
	}

}